/**
 * TabVD is a Virtual Desktop Client/Server designed specifically for connecting
 * from Tablet like devices.
 *
 * Copyright (C) 2011 Subhabrata Ghosh
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * DateTime.cpp
 *
 *  Created on: May 24, 2011
 *      Author: subhagho
 */

#include "DateTime.h"

namespace tabvd {

	DateTime::DateTime() {
		time(&timestamp);
		timeinfo = localtime(&timestamp);
		init();
	}

	DateTime::DateTime(long time) {
		timestamp = (time_t) time;
		timeinfo = localtime(&timestamp);
		init();
	}

	DateTime::DateTime(DateTime& dt) {
		timestamp = (time_t) dt.getTimestamp();
		timeinfo = localtime(&timestamp);
		init();
	}

	DateTime::~DateTime() {
		if (buffptr)
			free(buffptr);
		if (usedBuffers) {
			std::vector<std::string*>::iterator it;
			for (it = usedBuffers->begin(); it < usedBuffers->end(); it++) {
				if (*it) {
					delete *it;
				}
			}
			delete usedBuffers;
		}
		usedBuffers = NULL;
		buffptr = (char*) NULL;
	}

	void DateTime::init() {
		usedBuffers = new std::vector<std::string*>();

		sz_buffptr = 124;
		buffptr = (char*) malloc(sizeof(char) * sz_buffptr);
	}

	long DateTime::getTimestamp() {
		return (long) timestamp;
	}

	long DateTime::diff(DateTime& dt) {
		return (long) (timestamp - dt.timestamp);
	}

	std::string* DateTime::toString() {
		return toString(_DEFAULT_DATE_FORMAT_);
	}

	std::string* DateTime::toString(std::string format) {
		if (buffptr && usedBuffers) {
			memset(buffptr, 0, sz_buffptr);
			strftime(buffptr, sz_buffptr, format.c_str(), timeinfo);
			std::string* ptr = new std::string(buffptr);

			usedBuffers->push_back(ptr);

			return ptr;
		}
		return NULL;
	}
	DateTime* DateTime::now() {
		time(&timestamp);
		timeinfo = localtime(&timestamp);

		return this;
	}
}
